package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * create 2023/6/19 10:50
 */


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        HashMap<String, Object> userMap = new HashMap<>();
        String password = dto.getPassword();
        //1.根据账号和密码是否存在判断登陆类型
        String phone = dto.getPhone();
        if (!StringUtils.isEmpty(phone) && !StringUtils.isEmpty(password)) {
            //2.不为空，则校验用户密码，校验通过根据用户id生成token和user返回给前端
            ApUser user = this.getOne(new LambdaQueryWrapper<ApUser>().eq(ApUser::getPhone, phone));
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
            }
            String salt = user.getSalt();
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!pwd.equals(user.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
            userMap.put("token",token );
            user.setPassword("");
            user.setSalt("");
            userMap.put("user", user);
        }else {
            userMap.put("token", AppJwtUtil.getToken(0L));
        }
        //3.为空，则是游客登陆，使用0生成token返回
        return ResponseResult.okResult(userMap);
    }
}
